<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

set_time_limit(600);

class JFX_Module_Jfxbup extends JFX_Module{

    public $keyname = 'jfxbup';
    public $title = 'JFX Backup';

    public function __construct(){
        parent::__construct();
        if(!JFX_Module::isInstalled($this->keyname)) return;


        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $VIEW = JFX::registry('JFX_View');
        $lastRun = $DB->oneValue($CONFIG->dbprefix.'jfxbup_config', 'v', "k = 'last_run'");
        $lastRun = explode(',', $lastRun);
        $cron = $DB->oneValue($CONFIG->dbprefix.'jfxbup_config', 'v', "k = 'cron'");
        $cron = explode(',', $cron);

        $doBup = false;

        if(($cron[4] == '*' || $cron[4] == (int) date('w')) && $lastRun[4] != date('w')){
            $doBup = true;
        }
        if(($cron[3] == '*' || $cron[3] == (int) date('n')) && $lastRun[3] != date('n')){
            $doBup = true;
        }
        if(($cron[2] == '*' || $cron[2] == (int) date('j')) && $lastRun[2] != date('j')){
            $doBup = true;
        }
        if(($cron[1] == '*' || (int) $cron[1] == (int) date('H')) && $lastRun[1] != date('H')){
            $doBup = true;
        }
        if(($cron[0] == '*' || $cron[0] == (int) date('i')) && $lastRun[0] != (int) date('i')){
            $doBup = true;
        }

        if($doBup && get('dobup')==1){
            $this->doBackup();
        }else if($doBup){
            // schedule bup to run in ajax so the users page load performance is not impacted
            $VIEW->addJs(
                '$(document).ready(function(){$.get("'.$CONFIG->baseUrl.'/?dobup=1", {}, function(){});});'
            );
        }

    }

    public function admin($url){

        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $SMARTY->assign('actionUrl', $url);

        $this->addStylesheet('admin.css');

        $dirname = str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__));

        $tabs = array(
            array(
                'keyname' => 'settings',
                'title' => 'Backup Settings',
                'url' => $url.'/settings'
            ),
            array(
                'keyname' => 'restore',
                'title' => 'Restore Backup',
                'url' => $url.'/restore'
            )
        );


        // find our selected tab
        $urlParts = explode('?', THIS_PAGE_URL);
        $urlParts = explode('/', $urlParts[0]);
        foreach($urlParts as $k=>$v){
            if($v == $this->keyname) break;
        }

        $selectedTab = (array_key_exists($k+1, $urlParts))
            ? $urlParts[$k+1]
            : ''
            ;

        if($selectedTab == ''){
            $selectedTab = 'settings';
        }

        foreach($tabs as $k=>$tab){
            if($selectedTab == $tab['keyname']){
                $tabs[$k]['class_name'] = 'selected';
            }
        }

        include('admin-actions/tabs.php');

        $selectedTab = str_replace('../', '/', $selectedTab);

        echo '<div id="cst-admin-tab-content"><div id="cst-admin-tab-content-inner">';
            if(file_exists($dirname.'/admin-actions/'.$selectedTab.'.php')) include('admin-actions/'.$selectedTab.'.php');
            else echo $selectedTab.'.php does not exists';
        echo '</div></div>';





    }



    public function doBackup(){
        $DB = JFX::registry('db');
        //phpinfo();
        $CONFIG = JFX::registry('config');

        $os = $this->getConfig('operating_system');
        $path = $this->getConfig('path_to_mysqldump');



        if($os != 'windows' && $os != 'unix'){
          // invalid operating system
          return;
        }

        // update our last run time
        $lastRun = date('i').','.date('H').','.date('j').','.date('n').','.date('w');
        $DB->update($CONFIG->dbprefix.'jfxbup_config', array('v'=>$lastRun), "k = 'last_run'");

        $tables = $DB->oneValue($CONFIG->dbprefix.'jfxbup_config', 'v', "k = 'tables'");
        $tables = explode(',', $tables);
        $tstamp = date('Ymd-Hi');
        if(is_dir($CONFIG->modulesDir.'/'.$this->keyname.'/bups/'.$tstamp)) unlink_directory($CONFIG->modulesDir.'/'.$this->keyname.'/bups/'.$tstamp);
        //echo $CONFIG->modulesDir.'/'.$this->keyname.'/bups/'.$tstamp;
        @mkdir($CONFIG->modulesDir.'/'.$this->keyname.'/bups/'.$tstamp);



        if($os == 'unix'){
            echo '<h2>Backup runs on unix at '.$tstamp.'</h2>';
          foreach($tables as $k=>$v){
              echo $v.'<br />';
            $q = "{$path} -u {$CONFIG->dbuser} -p{$CONFIG->dbpassword} {$CONFIG->dbname} {$v} > '{$CONFIG->modulesDir}/{$this->keyname}/bups/{$tstamp}/{$v}.sql'";
            //echo $q.'<br />';
            exec($q);
          }

        }else if($os == 'windows'){
            echo '<h2>Backup runs on windows at '.$tstamp.'</h2>';
          foreach($tables as $k=>$v){
            $q = "{$path} --add-drop-table --host={$CONFIG->dbhost} --user={$CONFIG->dbuser} --password={$CONFIG->dbpassword} --databases {$CONFIG->dbname} {$v} > \"{$CONFIG->modulesDir}/{$this->keyname}/bups/{$tstamp}/{$v}.sql\"";
            $err = array();
            if(!exec($q, $err)){
              //echo 'failed to exec '.$q.print_r($err, true);
              continue;
            }
          }
        }

        // compress the backup
        $filename = $CONFIG->modulesDir.'/'.$this->keyname.'/bups/'.$tstamp.'.tgz';
        $gzip = new gzip_file($filename);
        $options = array(
            'basedir' => $CONFIG->modulesDir.'/'.$this->keyname.'/bups',
            'name' => $tstamp.'.tgz',
            'storepaths' => 0
        );
        $gzip->set_options($options);
        $gzip->add_files($CONFIG->modulesDir.'/'.$this->keyname.'/bups/'.$tstamp.'/*.sql');
        $gzip->create_archive();

        // remove uncompressed files to save disk space
        @unlink_directory($CONFIG->modulesDir.'/'.$this->keyname.'/bups/'.$tstamp);

    }






    public function install(){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        if((int) ini_get('safe_mode')==1 || strtolower(ini_get('safe_mode'))=='on'){
            JFX::addError('Safe mode is enabled, you need to disable it so I can use mysqldump. Put the following line in your .htaccess file:');
            JFX::addError('php_value safe_mode "0"');
            return false;
        }

        require('install/install.php');
    }

    public function uninstall(){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        require('install/uninstall.php');
    }
}